package com.emm.yixun.marketing.service.impl;

import java.util.Date;
import java.util.List;

import javax.jws.WebService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.BusinessAbnormaService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.SignedService;
import com.emm.yixun.basic.service.SubscribeService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.model.BusinessAbnorma;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.Signed;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.AbnormaBusinessView;
import com.emm.yixun.common.model.dto.BusinessAbnormaDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.model.enums.BusinessAbnormaEnum;
import com.emm.yixun.common.model.enums.BusinessTypeEnum;
import com.emm.yixun.common.model.enums.RoomStatusEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.marketing.service.BusinessAbnormaServiceFacade;

@Service("businessAbnormaServiceFacade")
@WebService(name = "com.emm.yixun.marketing.service.BusinessAbnormaServiceFacade")
public class BusinessAbnormaServiceFacadeImpl implements BusinessAbnormaServiceFacade {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private BusinessAbnormaService service;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private SubscribeService subscribeService;

	@Autowired
	private ProjectRoomService projectRoomService;

	@Autowired
	private SignedService signedService;

	@Autowired
	private UserService userService;

	@Override
	public Response<BusinessAbnormaDto> save(BusinessAbnormaDto dto) {
		Response<BusinessAbnormaDto> response = new Response<BusinessAbnormaDto>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			BusinessAbnormaDto mDto = service.create(dto);
			if (null == mDto) {
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(BusinessAbnormaDto dto, Boolean selective) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == selective || null == dto || null == dto.getId()) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}

			if (selective) {
				int count = service.update(dto);
				if (count > 0) {
					response.success(Integer.valueOf(count));
				} else {
					response.fail("90001", "更新数据失败");
				}
			} else {
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			BusinessAbnormaDto mDto = new BusinessAbnormaDto();
			mDto.setId(id);
			int count = service.destroy(mDto);
			if (count > 0) {
				response.success(Integer.valueOf(count));
			} else {
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<BusinessAbnorma> findById(Long id) {
		Response<BusinessAbnorma> response = new Response<BusinessAbnorma>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			BusinessAbnorma entity = service.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<BusinessAbnorma> findByDto(BusinessAbnormaDto dto) {
		ResponseList<BusinessAbnorma> response = new ResponseList<BusinessAbnorma>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<BusinessAbnorma> list = service.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<BusinessAbnorma> findPageByDto(BusinessAbnormaDto dto, Integer begin, Integer row) {
		Page<BusinessAbnorma> response = new Page<BusinessAbnorma>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<BusinessAbnorma> page = service.getPageModel(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public AbnormaBusinessView findAbnormaBusinessById(Long id) {
		try {
			return converAbnorma(id);
		} catch (Exception e) {
			logger.error("findAbnormaBusinessById erro: ", e);
		}
		return null;
	}

	public AbnormaBusinessView converAbnorma(Long id) {
		AbnormaBusinessView bus = new AbnormaBusinessView();
		Subscribe subscribe = subscribeService.selectById(id);
		bus = BeanUtil.convert2T(bus, subscribe);
		bus.setBusinessType(BusinessTypeEnum.SUBSCRIBE.getDes());
		Customer customer = customerService.selectById(subscribe.getCustomerId());
		bus.setCustomerName(customer.getCustomerName());
		bus.setCustomerId(customer.getId());
		bus.setReceivables(subscribe.getDepositReceivable());
		bus.setContractDate(subscribe.getSubscribeDate());
		bus.setContractDateStr(DateUtils.DateToString(subscribe.getSubscribeDate(), DateStyle.YYYY_MM_DD.getValue()));
		com.emm.yixun.common.model.ProjectRoom room = projectRoomService.selectById(subscribe.getRoomId());
		bus.setRoomCombox(room.getCombinedName());
		return bus;
	}

	@Override
	public Response<Long> saveChangeHouseInfo(User user, BusinessAbnormaDto entity) throws Exception{
		Response<Long> response = new Response<Long>();
		ProjectRoom room = projectRoomService.selectById(entity.getNewRoomId());
		
		Subscribe subscribe = subscribeService.selectById(entity.getBusinessId());
		if (subscribe.getRoomId().compareTo(entity.getNewRoomId()) == 0) {
			response.setEntity(Long.valueOf("-1"));
			response.setSuccess(false);
			response.setResultMessage("所换房间不能跟原房间一样!");
			return response;
		}
		
		if (!room.getRoomStatus().equals(RoomStatusEnum.VENDIBILITY.getNo())
				&& !room.getRoomStatus().equals(RoomStatusEnum.RESERVE.getNo())) {
			response.setEntity(Long.valueOf("-1"));
			response.setSuccess(false);
			response.setResultMessage("所换房间状态只能是可售,认筹才能换房!");
			return response;
		}
		
		BusinessAbnormaDto busEntity = new BusinessAbnormaDto();
		busEntity.setBusinessId(entity.getBusinessId());
		busEntity.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_1.getNo());
		busEntity.setOrders(" t.create_time desc ");
		List<BusinessAbnorma> baList=service.selectListByDto(busEntity);
		for(BusinessAbnorma ba : baList){
			String auditStatus=ba.getAuditStatus();
			if(auditStatus.equals(AuditStatusEnum.AUDIT.getNo())){
				response.setEntity(Long.valueOf("-1"));
				response.setSuccess(false);
				response.setResultMessage("此条认购信息,已经存在换房记录!");
				return response;
			}
			
		}
		entity.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_1.getNo());
		entity.setAuditStatus(AuditStatusEnum.TOSUBMIT.getNo());
		entity.setMerchantId(user.getMerchantId());
		entity.setAccessCode(room.getProjectCode());
		entity.setUserCode(user.getUserCode());
		entity.setCreateUserId(user.getId());
		entity.setCreateTime(new Date());
		entity.setUpdateTime(new Date());
		entity.setDelFlag("0");
		service.create(entity);
		response.setEntity(entity.getId());
		response.setSuccess(true);
		return response;
	}

	@Override
	public AbnormaBusinessView findAbormaBusinessDetailById(Long id) {
		Long abId = null;
		try {
			AbnormaBusinessView bus = converAbnorma(id);
			BusinessAbnormaDto babDto = new BusinessAbnormaDto();
			babDto.setBusinessId(new Long(id));
			babDto.setBusinessType("1");
			babDto.setOrders(" t.id desc ");
			List<BusinessAbnorma> busineList = service.selectListByDto(babDto);
			if (busineList != null && busineList.size() > 0) {
				abId = busineList.get(0).getId();
				bus.setAuditStatus(busineList.get(0).getAuditStatus());
				bus.setProcInstId(busineList.get(0).getProcInstId());
			}
			if (abId != null) {
				bus.setBusinessType("换房申请");
				BusinessAbnorma abnorma = service.selectById(abId);
				bus.setBfdTotalPrice(abnorma.getBfdTotalPrice());
				bus.setCalculateArea1(abnorma.getCalculateArea());
				bus.setBfdUnitPrice(abnorma.getBfdUnitPrice());
				bus.setRemark(abnorma.getRemark());
				bus.setApplyDate(abnorma.getCreateTime());
				bus.setApplyDateStr(DateUtils.DateToString(abnorma.getCreateTime(), DateStyle.YYYY_MM_DD_HH_MM_SS.getValue()));
				User user = userService.selectById(abnorma.getCreateUserId());
				bus.setManagersName(user.getUserName());
				ProjectRoom projectRoom = projectRoomService.selectById(busineList.get(0).getNewRoomId());
				bus.setNewRoomName(projectRoom.getCombinedName());
			}
			return bus;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@Override
	public Response<BusinessAbnormaDto> signedChangeRoom(BusinessAbnormaDto entity, User user) throws Exception {
		Response<BusinessAbnormaDto> response = new Response<BusinessAbnormaDto>();
		ProjectRoom room = projectRoomService.selectById(entity.getNewRoomId());
		entity.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_1.getNo());
		entity.setAuditStatus(AuditStatusEnum.TOSUBMIT.getNo());
		Signed signed = signedService.selectById(entity.getBusinessId());
		if (signed.getRoomId().compareTo(entity.getNewRoomId()) == 0) {
			response.setSuccess(false);
			response.setResultMessage("所换房间不能跟原房间一样!");
		} else {
			if (!room.getRoomStatus().equals(RoomStatusEnum.VENDIBILITY.getNo())) {
				response.setSuccess(false);
				response.setResultMessage("房源非可售,不能换房!");
			} else {
				BusinessAbnormaDto baDto = new BusinessAbnormaDto();
				baDto.setBusinessId(entity.getBusinessId());
				baDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_3.getNo());
				baDto.setAuditStatus(AuditStatusEnum.TOSUBMIT.getNo());
				List<BusinessAbnorma> baList = service.selectListByDto(baDto);
				if (baList.size() > 0) {
					response.setSuccess(false);
					response.setResultMessage("存在待审核换房申请,暂不能换房!");
				} else {
					baDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
					baList = service.selectListByDto(baDto);
					if (baList.size() > 0) {
						response.setSuccess(false);
						response.setResultMessage("存在审核中换房申请,暂不能换房!");
					} else {
						entity.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_3.getNo());
						entity.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
						entity.setMerchantId(user.getMerchantId());
						entity.setAccessCode(room.getProjectCode());
						entity.setUserCode(user.getUserCode());
						entity.setCreateUserId(user.getId());
						entity.setCreateTime(new Date());
						entity.setUpdateTime(new Date());
						entity.setDelFlag("0");
						BusinessAbnormaDto dto = service.create(entity);
						response.setSuccess(true);
						response.setEntity(dto);
					}
				}
			}
		}
		return response;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.emm.yixun.marketing.service.BusinessAbnormaServiceFacade#selectByDto(com.emm.yixun.common.model.dto.
	 * BusinessAbnormaDto)
	 */
	@Override
	public Response<Boolean> selectByDto(BusinessAbnormaDto entity) {
		Response<Boolean> response = new Response<Boolean>();
		try {
			BusinessAbnormaDto busEntity = new BusinessAbnormaDto();
			busEntity.setBusinessId(entity.getBusinessId());
			busEntity.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_1.getNo());
			busEntity.setOrders(" t.id desc ");
			List<BusinessAbnorma> baList = service.selectListByDto(busEntity);
			for(BusinessAbnorma ba : baList){
				String auditStatus=ba.getAuditStatus();
				if(auditStatus.equals(AuditStatusEnum.AUDIT.getNo())){
					response.setEntity(false);
					response.setSuccess(false);
					response.setResultMessage("此条认购信息,已经存在换房记录!");
					return response;
				}
				
			}
			response.setSuccess(true);
		} catch (Exception e) {
			logger.error("selectByDto error: ", e);
		}
		return response;
	}

}
